<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="keywords" content="Hexo Theme Keep">
    <meta name="description" content="Hexo Theme Keep">
    <meta name="author" content="Da">
    
    <title>
        
            简单模拟mustache模板引擎实现 |
        
        Da的个人博客
    </title>
    
<link rel="stylesheet" href="/css/style.css">

    <link rel="shortcut icon" href="/images/logo.svg">
    
<link rel="stylesheet" href="/css/font-awesome.min.css">

    <script id="hexo-configurations">
    let KEEP = window.KEEP || {};
    KEEP.hexo_config = {"hostname":"da9527.gitee.io","root":"/","language":"zh-CN","path":"search.json"};
    KEEP.theme_config = {"toc":{"enable":true,"number":false,"expand_all":false,"init_open":false},"style":{"primary_color":"#CC0000","avatar":"/images/avatar.svg","favicon":"/images/logo.svg","article_img_align":"left","left_side_width":"260px","content_max_width":"920px","hover":{"shadow":true,"scale":true},"first_screen":{"enable":true,"background_img":"/images/bg.svg","description":"我不怕千万人阻挡,只怕自己投降"},"scroll":{"progress_bar":{"enable":false},"percent":{"enable":false}}},"local_search":{"enable":true,"preload":false},"code_copy":{"enable":true,"style":"default"},"pjax":{"enable":true},"lazyload":{"enable":true},"version":"3.4.2"};
    KEEP.language_ago = {"second":"%s 秒前","minute":"%s 分钟前","hour":"%s 小时前","day":"%s 天前","week":"%s 周前","month":"%s 月前","year":"%s 年前"};
  </script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
<div class="progress-bar-container">
    

    
        <span class="pjax-progress-bar"></span>
        <span class="pjax-progress-icon">
            <i class="fas fa-circle-notch fa-spin"></i>
        </span>
    
</div>


<main class="page-container">

    

    <div class="page-main-content">

        <div class="page-main-content-top">
            <header class="header-wrapper">

    <div class="header-content">
        <div class="left">
            <a class="logo-title" href="/">
                Da的个人博客
            </a>
        </div>

        <div class="right">
            <div class="pc">
                <ul class="menu-list">
                    
                        <li class="menu-item">
                            <a class=""
                               href="/"
                            >
                                首页
                            </a>
                        </li>
                    
                        <li class="menu-item">
                            <a class=""
                               href="/archives"
                            >
                                归档
                            </a>
                        </li>
                    
                        <li class="menu-item">
                            <a class=""
                               href="/about"
                            >
                                关于
                            </a>
                        </li>
                    
                    
                        <li class="menu-item search search-popup-trigger">
                            <i class="fas fa-search"></i>
                        </li>
                    
                </ul>
            </div>
            <div class="mobile">
                
                    <div class="icon-item search search-popup-trigger"><i class="fas fa-search"></i></div>
                
                <div class="icon-item menu-bar">
                    <div class="menu-bar-middle"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="header-drawer">
        <ul class="drawer-menu-list">
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/">首页</a>
                </li>
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/archives">归档</a>
                </li>
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/about">关于</a>
                </li>
            
        </ul>
    </div>

    <div class="window-mask"></div>

</header>


        </div>

        <div class="page-main-content-middle">

            <div class="main-content">

                
                    <div class="fade-in-down-animation">
    <div class="article-content-container">

        <div class="article-title">
            <span class="title-hover-animation">简单模拟mustache模板引擎实现</span>
        </div>

        
            <div class="article-header">
                <div class="avatar">
                    <img src="/images/avatar.svg">
                </div>
                <div class="info">
                    <div class="author">
                        <span class="name">Da</span>
                        
                            <span class="author-label">Lv4</span>
                        
                    </div>
                    <div class="meta-info">
                        <div class="article-meta-info">
    <span class="article-date article-meta-item">
        <i class="fas fa-edit"></i>&nbsp;2021-08-01 17:48:05
    </span>
    
    

    
    
        <span class="article-wordcount article-meta-item">
            <i class="fas fa-file-word"></i>&nbsp;<span>1.7k 字</span>
        </span>
    
    
        <span class="article-min2read article-meta-item">
            <i class="fas fa-clock"></i>&nbsp;<span>8 分钟</span>
        </span>
    
    
        <span class="article-pv article-meta-item">
            <i class="fas fa-eye"></i>&nbsp;<span id="busuanzi_value_page_pv"></span>
        </span>
    
</div>

                    </div>
                </div>
            </div>
        

        <div class="article-content markdown-body">
            <h2 id="简单模拟mustache模板引擎实现"><a href="#简单模拟mustache模板引擎实现" class="headerlink" title="简单模拟mustache模板引擎实现"></a>简单模拟mustache模板引擎实现</h2><p>mustache.js 是一个简单强大的 JavaScript 模板引擎。<a class="link"   target="_blank" rel="noopener" href="http://mustache.github.io/" >官网<i class="fas fa-external-link-alt"></i></a></p>
<p><strong>html页面</strong></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>模板字符串<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">style</span>&gt;</span></span><br><span class="line">      .diy&#123;</span><br><span class="line"><span class="css">        <span class="attribute">color</span>: red;</span></span><br><span class="line">      &#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;app&quot;</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;diy&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">          &#123;&#123;#students&#125;&#125;</span><br><span class="line">          <span class="tag">&lt;<span class="name">li</span>&gt;</span>学生&#123;&#123;name&#125;&#125;<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">ol</span>&gt;</span></span><br><span class="line">            &#123;&#123;#hobbies&#125;&#125;</span><br><span class="line">            <span class="tag">&lt;<span class="name">li</span>&gt;</span>&#123;&#123;.&#125;&#125;<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">            &#123;&#123;/hobbies&#125;&#125;</span><br><span class="line">          <span class="tag">&lt;/<span class="name">ol</span>&gt;</span></span><br><span class="line">          &#123;&#123;/students&#125;&#125;</span><br><span class="line">        <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 引入扫描器 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./Scanner.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 把tokens嵌套 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./NestTokens.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 把模板字符串转成tokens --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./ParseTemplateToTokens.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 处理连续.的对象 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./LookUp.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 处理折叠的token --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./ParseArray.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 生成dom --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./RenderTemplate.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- main方法 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./main.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> temStr = <span class="built_in">document</span>.getElementById(<span class="string">&quot;app&quot;</span>).innerHTML;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">const</span> data = &#123;</span></span><br><span class="line">        students:[</span><br><span class="line"><span class="javascript">          &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;小明&#x27;</span>,<span class="string">&#x27;hobbies&#x27;</span>:[<span class="string">&#x27;吃饭&#x27;</span>,<span class="string">&#x27;睡觉&#x27;</span>]&#125;,</span></span><br><span class="line"><span class="javascript">          &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;小红&#x27;</span>,<span class="string">&#x27;hobbies&#x27;</span>:[<span class="string">&#x27;吃饭&#x27;</span>,<span class="string">&#x27;睡觉&#x27;</span>]&#125;,</span></span><br><span class="line"><span class="javascript">          &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;小花&#x27;</span>,<span class="string">&#x27;hobbies&#x27;</span>:[<span class="string">&#x27;吃饭&#x27;</span>,<span class="string">&#x27;睡觉&#x27;</span>]&#125;</span></span><br><span class="line">        ]</span><br><span class="line">      &#125;;</span><br><span class="line">      SSG_TemplateEngine.render(temStr, data);</span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>



<p><strong>扫描类Scanner.js</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *  扫描器类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Scanner</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">templateStr</span>)</span>&#123;</span><br><span class="line">        <span class="comment">// 将templateStr写到类上</span></span><br><span class="line">        <span class="built_in">this</span>.templateStr = templateStr</span><br><span class="line">        <span class="comment">// 定义指针</span></span><br><span class="line">        <span class="built_in">this</span>.pos = <span class="number">0</span></span><br><span class="line">        <span class="comment">// 尾巴,一开始是模板字符串原文</span></span><br><span class="line">        <span class="built_in">this</span>.tail = templateStr</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 让指针进行扫描,直到遇到指定内容结束,并且返回结束前路过的文字</span></span><br><span class="line">    <span class="function"><span class="title">scanUtil</span>(<span class="params">stopStr</span>)</span>&#123;</span><br><span class="line">        <span class="comment">// 记录开始扫描时指针的位置</span></span><br><span class="line">        <span class="keyword">const</span> pos_backup = <span class="built_in">this</span>.pos</span><br><span class="line">        <span class="comment">// 当尾巴不是指定内容时并且指针位置没有达到模板字符串的终点时,说明还没有扫到,让指针移动</span></span><br><span class="line">        <span class="keyword">while</span>(<span class="built_in">this</span>.tail.indexOf(stopStr) != <span class="number">0</span> &amp;&amp; <span class="built_in">this</span>.pos &lt; <span class="built_in">this</span>.templateStr.length)&#123;</span><br><span class="line">            <span class="built_in">this</span>.pos++</span><br><span class="line">            <span class="comment">// 改变尾巴,删掉走过的文字</span></span><br><span class="line">            <span class="built_in">this</span>.tail = <span class="built_in">this</span>.templateStr.substr(<span class="built_in">this</span>.pos)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 返回走过的字符</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.templateStr.substring(pos_backup,<span class="built_in">this</span>.pos)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 走过指定内容,没有返回值</span></span><br><span class="line">    <span class="function"><span class="title">scan</span>(<span class="params">tag</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(<span class="built_in">this</span>.tail.indexOf(tag) === <span class="number">0</span>)&#123;</span><br><span class="line">            <span class="comment">// tag有多长,就让指针向后移多少位,这个方法用来过&#x27;&#123;&#123;&#x27;或者&#x27;&#125;&#125;&#x27;</span></span><br><span class="line">            <span class="built_in">this</span>.pos += tag.length<span class="comment">//改变指针的位置</span></span><br><span class="line">            <span class="comment">// 改变尾巴,删掉走过的文字</span></span><br><span class="line">            <span class="built_in">this</span>.tail = <span class="built_in">this</span>.templateStr.substr(<span class="built_in">this</span>.pos)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>折叠tokens的方法NestTokens.js</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 折叠tokens,嵌套</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">nestTokens</span>(<span class="params">tokens</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 折叠后的token数组</span></span><br><span class="line">    <span class="keyword">const</span> nestedTokens = []</span><br><span class="line">    <span class="comment">// 栈结构: 存放token,先进后出</span></span><br><span class="line">    <span class="keyword">const</span> sections = []</span><br><span class="line">    <span class="comment">// 收集器,指向nestedTokens,引用类型值,所以指向的是同一个数组</span></span><br><span class="line">    <span class="comment">// 收集器的指向会变化,当遇到#时会指向当前token下标为2的新数组</span></span><br><span class="line">    <span class="keyword">let</span> collector = nestedTokens</span><br><span class="line">    <span class="comment">// 遍历原始的tokens</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; tokens.length; i++)&#123;</span><br><span class="line">        <span class="keyword">let</span> token = tokens[i]</span><br><span class="line">        <span class="keyword">switch</span>(token[<span class="number">0</span>])&#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;#&#x27;</span>:</span><br><span class="line">                <span class="comment">//    往收集器中加入这个token</span></span><br><span class="line">                collector.push(token)</span><br><span class="line">                <span class="comment">// 入栈</span></span><br><span class="line">                sections.push(token)</span><br><span class="line">                <span class="comment">// 更换收集器,让token下标为2的地方放置新收集的token</span></span><br><span class="line">                collector = token[<span class="number">2</span>] = []</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;/&#x27;</span>:</span><br><span class="line">                <span class="comment">// 出栈,pop()会返回刚刚弹出的项</span></span><br><span class="line">                sections.pop()</span><br><span class="line">                <span class="comment">// 改变收集器为栈结构的队尾(队尾是栈顶)那项下标为2的数组(先判断sections数组的长度是否大于0)</span></span><br><span class="line">                collector = sections.length &gt; <span class="number">0</span> ? sections[sections.length - <span class="number">1</span>][<span class="number">2</span>] : nestedTokens</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                collector.push(token)</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> nestedTokens</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>处理扫描内容,转成tokens数组ParseTemplateToTokens.js</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 处理扫描内容,转成tokens数组</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">parseTemplateToTokens</span>(<span class="params">templateStr</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> tokens = []</span><br><span class="line">     <span class="comment">// 实例化Scanner类,用于扫描</span></span><br><span class="line">     <span class="keyword">const</span> scanner = <span class="keyword">new</span> Scanner(templateStr)</span><br><span class="line">    <span class="comment">//  定义保存走过的文字</span></span><br><span class="line">     <span class="keyword">let</span> words</span><br><span class="line">     <span class="comment">// 扫描字符串,如果指针没有走到模板字符串的尽头就继续扫描</span></span><br><span class="line">     <span class="keyword">while</span>(scanner.pos != templateStr.length)&#123;</span><br><span class="line">         <span class="comment">// 扫描&#123;&#123;前的文字</span></span><br><span class="line">         words = scanner.scanUtil(<span class="string">&#x27;&#123;&#123;&#x27;</span>)</span><br><span class="line">        <span class="comment">// 如果不是空字符就加入tokens数组</span></span><br><span class="line">        <span class="keyword">if</span>(words !== <span class="string">&#x27;&#x27;</span>)&#123;</span><br><span class="line">            <span class="comment">// 去除一些多余的空格</span></span><br><span class="line">            <span class="keyword">let</span> isKG = <span class="literal">false</span><span class="comment">//标识是不是空格</span></span><br><span class="line">            <span class="keyword">let</span> _worlds = <span class="string">&#x27;&#x27;</span></span><br><span class="line">            <span class="comment">// 遍历words</span></span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; words.length; i++)&#123;</span><br><span class="line">                <span class="comment">// 如果不是空格就拼接</span></span><br><span class="line">                <span class="keyword">if</span>(words[i] !== <span class="string">&#x27; &#x27;</span>)&#123;</span><br><span class="line">                    _worlds += words[i]</span><br><span class="line">                &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                    <span class="comment">// 如果是空格,当它在标签里才拼接</span></span><br><span class="line">                    <span class="keyword">if</span>(!isKG)&#123;</span><br><span class="line">                        _worlds += words[i]</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">if</span>(words[i] === <span class="string">&#x27;&lt;&#x27;</span>)&#123;</span><br><span class="line">                        <span class="comment">// 标识进入标签内</span></span><br><span class="line">                        isKG = <span class="literal">true</span></span><br><span class="line">                    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(words[i] === <span class="string">&#x27;&gt;&#x27;</span>)&#123;</span><br><span class="line">                        <span class="comment">// 标识标签结束</span></span><br><span class="line">                        isKG = <span class="literal">false</span></span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            words = _worlds</span><br><span class="line">            tokens.push([<span class="string">&#x27;text&#x27;</span>,words])</span><br><span class="line">        &#125;</span><br><span class="line">         <span class="comment">// 略过&#123;&#123;</span></span><br><span class="line">         scanner.scan(<span class="string">&quot;&#123;&#123;&quot;</span>)</span><br><span class="line">        <span class="comment">// 扫描&#125;&#125;前的文字</span></span><br><span class="line">         words = scanner.scanUtil(<span class="string">&#x27;&#125;&#125;&#x27;</span>)</span><br><span class="line">         <span class="comment">// 如果不是空字符就加入tokens数组</span></span><br><span class="line">         <span class="keyword">if</span>(words !== <span class="string">&#x27;&#x27;</span>)&#123;<span class="comment">//这里存的就是&#123;&#123;&#125;&#125;里面的文字</span></span><br><span class="line">            <span class="keyword">if</span>(words[<span class="number">0</span>] === <span class="string">&#x27;#&#x27;</span>)&#123;<span class="comment">//从#后面开始存</span></span><br><span class="line">                tokens.push([<span class="string">&#x27;#&#x27;</span>,words.substring(<span class="number">1</span>)])</span><br><span class="line">            &#125;<span class="keyword">else</span> <span class="keyword">if</span>(words[<span class="number">0</span>] === <span class="string">&#x27;/&#x27;</span>)&#123;<span class="comment">//从/后面开始存</span></span><br><span class="line">                tokens.push([<span class="string">&#x27;/&#x27;</span>,words.substring(<span class="number">1</span>)])</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;<span class="comment">//直接存</span></span><br><span class="line">                tokens.push([<span class="string">&#x27;name&#x27;</span>,words])</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="comment">// 略过&#125;&#125;</span></span><br><span class="line">         scanner.scan(<span class="string">&#x27;&#125;&#125;&#x27;</span>)</span><br><span class="line">     &#125;</span><br><span class="line">    <span class="comment">//  返回折叠后的tokens</span></span><br><span class="line">    <span class="keyword">return</span> nestTokens(tokens)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>在对象中寻找连续点符号的属性LookUp.js</strong>      </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 在对象中寻找连续点符号的属性</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">lookup</span>(<span class="params">dataObj, keyName</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 判断keyName中有没有.并且keyName不能是.本身</span></span><br><span class="line">    <span class="keyword">if</span>(keyName.indexOf(<span class="string">&#x27;.&#x27;</span>) != -<span class="number">1</span> &amp;&amp; keyName !== <span class="string">&#x27;.&#x27;</span>)&#123;</span><br><span class="line">        <span class="comment">// 如果有就拆开</span></span><br><span class="line">        <span class="keyword">const</span> keys = keyName.split(<span class="string">&#x27;.&#x27;</span>)</span><br><span class="line">        <span class="comment">// 定义一个临时变量用于周转,一层一层拆开对象</span></span><br><span class="line">        <span class="keyword">let</span> temp = dataObj</span><br><span class="line">        <span class="comment">// 遍历拆分的数组</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; keys.length; i++)&#123;</span><br><span class="line">            temp = temp[keys[i]]</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 返回解析出来的对象</span></span><br><span class="line">        <span class="keyword">return</span> temp</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="comment">// 如果没有.,就返回对象中改键对应的值</span></span><br><span class="line">        <span class="keyword">return</span> dataObj[keyName]</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>处理数组,结合renderTemplate实现递归RenderTemplate.js</strong>  </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 让token数组与数据结合重新生成dom</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">renderTemplate</span>(<span class="params">tokens,data</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 结果字符串</span></span><br><span class="line">    <span class="keyword">let</span> domStr = <span class="string">&#x27;&#x27;</span></span><br><span class="line">    <span class="comment">// 遍历tokens</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; tokens.length; i++)&#123;</span><br><span class="line">        <span class="keyword">let</span> token = tokens[i]</span><br><span class="line">        <span class="comment">// 判断类型</span></span><br><span class="line">        <span class="keyword">if</span>(token[<span class="number">0</span>] === <span class="string">&#x27;text&#x27;</span>)&#123;</span><br><span class="line">            <span class="comment">// 表示&#123;&#123;&#125;&#125;外的内容,直接拼接</span></span><br><span class="line">            domStr += token[<span class="number">1</span>]</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span>(token[<span class="number">0</span>] === <span class="string">&#x27;name&#x27;</span>)&#123;</span><br><span class="line">            <span class="comment">// 表示&#123;&#123;&#125;&#125;里面的内容,从传入的对象中取值拼接</span></span><br><span class="line">            <span class="comment">// 用lookup函数处理有.的键</span></span><br><span class="line">            domStr += lookup(data,token[<span class="number">1</span>])</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span>(token[<span class="number">0</span>] === <span class="string">&#x27;#&#x27;</span>)&#123;</span><br><span class="line">            <span class="comment">// 表示有折叠的token,需要使用递归拆解出来</span></span><br><span class="line">            domStr += parseArray(token,data)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> domStr</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>main.js组合方法</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.SSG_TemplateEngine = &#123;</span><br><span class="line">    <span class="comment">// 渲染方法</span></span><br><span class="line">    <span class="function"><span class="title">render</span>(<span class="params">templateStr,data</span>)</span>&#123;</span><br><span class="line">        <span class="comment">// 解析模板字符串,让其变成token数组</span></span><br><span class="line">        <span class="keyword">const</span> tokens = parseTemplateToTokens(templateStr)</span><br><span class="line">        <span class="comment">// 让token数组与数据结合重新生成dom</span></span><br><span class="line">        <span class="keyword">const</span> domStr = renderTemplate(tokens,data)</span><br><span class="line">        <span class="comment">// 渲染模板</span></span><br><span class="line">        <span class="built_in">document</span>.getElementById(<span class="string">&quot;app&quot;</span>).innerHTML = domStr</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>​              </p>

        </div>

        
            <div class="post-copyright-info">
                <div class="article-copyright-info-container">
    <ul>
        <li>本文标题：简单模拟mustache模板引擎实现</li>
        <li>本文作者：Da</li>
        <li>创建时间：2021-08-01 17:48:05</li>
        <li>
            本文链接：https://da9527.gitee.io/2021/08/01/简单模拟mustache模板引擎实现/
        </li>
        <li>
            版权声明：本博客所有文章除特别声明外，均采用 <a class="license" target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">BY-NC-SA</a> 许可协议。转载请注明出处！
        </li>
    </ul>
</div>

            </div>
        

        
            <div class="article-nav">
                
                    <div class="article-prev">
                        <a class="prev"
                           rel="prev"
                           href="/2021/08/23/node%E6%93%8D%E4%BD%9Cmysql/"
                        >
                            <span class="left arrow-icon flex-center">
                              <i class="fas fa-chevron-left"></i>
                            </span>
                            <span class="title flex-center">
                                <span class="post-nav-title-item">node操作mysql</span>
                                <span class="post-nav-item">上一篇</span>
                            </span>
                        </a>
                    </div>
                
                
                    <div class="article-next">
                        <a class="next"
                           rel="next"
                           href="/2021/07/09/JDBC%E6%93%8D%E4%BD%9C%E5%B0%81%E8%A3%85%E5%B7%A5%E5%85%B7%E7%B1%BB/"
                        >
                            <span class="title flex-center">
                                <span class="post-nav-title-item">JDBC操作封装工具类</span>
                                <span class="post-nav-item">下一篇</span>
                            </span>
                            <span class="right arrow-icon flex-center">
                              <i class="fas fa-chevron-right"></i>
                            </span>
                        </a>
                    </div>
                
            </div>
        

        
    </div>
</div>


                
            </div>

        </div>

        <div class="page-main-content-bottom">
            <footer class="footer">
    <div class="info-container">
        <div class="copyright-info info-item">
            &copy;
            
              <span>2020</span>&nbsp;-&nbsp;
            
            2021&nbsp;<i class="fas fa-heart icon-animate"></i>&nbsp;<a href="/">Da</a>
        </div>
        
            <script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
            <div class="website-count info-item">
                
                    <span id="busuanzi_container_site_uv">
                        访问人数&nbsp;<span id="busuanzi_value_site_uv"></span>&ensp;
                    </span>
                
                
                    <span id="busuanzi_container_site_pv">
                        总访问量&nbsp;<span id="busuanzi_value_site_pv"></span>
                    </span>
                
            </div>
        
        <div class="theme-info info-item">
            由 <a target="_blank" href="https://hexo.io">Hexo</a> 驱动&nbsp;|&nbsp;主题&nbsp;<a class="theme-version" target="_blank" href="https://github.com/XPoet/hexo-theme-keep">Keep v3.4.2</a>
        </div>
        
    </div>
</footer>

        </div>
    </div>

    
        <div class="post-tools">
            <div class="post-tools-container">
    <ul class="tools-list">
        <!-- TOC aside toggle -->
        
            <li class="tools-item page-aside-toggle">
                <i class="fas fa-outdent"></i>
            </li>
        

        <!-- go comment -->
        
    </ul>
</div>

        </div>
    

    <div class="right-bottom-side-tools">
        <div class="side-tools-container">
    <ul class="side-tools-list">
        <li class="tools-item tool-font-adjust-plus flex-center">
            <i class="fas fa-search-plus"></i>
        </li>

        <li class="tools-item tool-font-adjust-minus flex-center">
            <i class="fas fa-search-minus"></i>
        </li>

        <li class="tools-item tool-expand-width flex-center">
            <i class="fas fa-arrows-alt-h"></i>
        </li>

        <li class="tools-item tool-dark-light-toggle flex-center">
            <i class="fas fa-moon"></i>
        </li>

        <!-- rss -->
        

        
            <li class="tools-item tool-scroll-to-top flex-center">
                <i class="fas fa-arrow-up"></i>
            </li>
        

        <li class="tools-item tool-scroll-to-bottom flex-center">
            <i class="fas fa-arrow-down"></i>
        </li>
    </ul>

    <ul class="exposed-tools-list">
        <li class="tools-item tool-toggle-show flex-center">
            <i class="fas fa-cog fa-spin"></i>
        </li>
        
    </ul>
</div>

    </div>

    
        <aside class="page-aside">
            <div class="post-toc-wrap">
    <div class="post-toc">
        <ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AE%80%E5%8D%95%E6%A8%A1%E6%8B%9Fmustache%E6%A8%A1%E6%9D%BF%E5%BC%95%E6%93%8E%E5%AE%9E%E7%8E%B0"><span class="nav-text">简单模拟mustache模板引擎实现</span></a></li></ol>
    </div>
</div>
        </aside>
    

    <div class="image-viewer-container">
    <img src="">
</div>


    
        <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
          <span class="search-input-field-pre">
            <i class="fas fa-keyboard"></i>
          </span>
            <div class="search-input-container">
                <input autocomplete="off"
                       autocorrect="off"
                       autocapitalize="off"
                       placeholder="搜索..."
                       spellcheck="false"
                       type="search"
                       class="search-input"
                >
            </div>
            <span class="popup-btn-close">
                <i class="fas fa-times"></i>
            </span>
        </div>
        <div id="search-result">
            <div id="no-result">
                <i class="fas fa-spinner fa-pulse fa-5x fa-fw"></i>
            </div>
        </div>
    </div>
</div>

    

</main>




<script src="/js/utils.js"></script>

<script src="/js/main.js"></script>

<script src="/js/header-shrink.js"></script>

<script src="/js/back2top.js"></script>

<script src="/js/dark-light-toggle.js"></script>



    
<script src="/js/local-search.js"></script>




    
<script src="/js/code-copy.js"></script>




    
<script src="/js/lazyload.js"></script>



<div class="post-scripts pjax">
    
        
<script src="/js/left-side-toggle.js"></script>

<script src="/js/libs/anime.min.js"></script>

<script src="/js/toc.js"></script>

    
</div>


    
<script src="/js/libs/pjax.min.js"></script>

<script>
    window.addEventListener('DOMContentLoaded', () => {
        const pjax = new Pjax({
            selectors: [
                'head title',
                '.page-container',
                '.pjax'
            ],
            history: true,
            debug: false,
            cacheBust: false,
            timeout: 0,
            analytics: false,
            currentUrlFullReload: false,
            scrollRestoration: false,
            // scrollTo: true,
        });

        document.addEventListener('pjax:send', () => {
            KEEP.utils.pjaxProgressBarStart();
        });

        document.addEventListener('pjax:complete', () => {
            KEEP.utils.pjaxProgressBarEnd();
            pjax.executeScripts(document.querySelectorAll('script[data-pjax], .pjax script'));
            KEEP.refresh();
        });
    });
</script>



<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/shizuku.model.json"},"display":{"position":"left","width":120,"height":240},"mobile":{"show":false},"log":false});</script></body>
</html>
